package com.saas.sys.buffer;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.PropertyUtils;

import com.saas.biz.commen.CommMethodMgr;
import com.saas.biz.paramMgr.ParamInfo;
import com.saas.sys.exp.SaasApplicationException;
import com.saas.sys.log.Logger;
import com.zhike.b2b.Constants;
import com.zhike.b2b.model.UserCore;

public class Buffers implements BufferIntf
{
  Buffer httpBuffer = new Buffer();
  static Buffer saasBuffer = new Buffer();
  Logger log = new Logger(this);
  CommMethodMgr comm = new CommMethodMgr();
  Object vo;
  String className;
  
  static
  {
	FileReader fr = null;
	BufferedReader br = null;
	String dir = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
	int inx = dir.indexOf("WEB-INF");
	if(inx>0)
		dir = dir.substring(0,inx);
    String flds = dir+"WEB-INF/saas.flds";
    try
    {
      fr = new FileReader(flds);
      br = new BufferedReader(fr);
      for (String str = br.readLine(); str != null; str = br.readLine())
      {
        if ((str.trim().equalsIgnoreCase("")) || (str.substring(0, 1).equalsIgnoreCase("#")))
          continue;
        String[] arrayOfString = str.split(",");
        Map<String,String> hm = new HashMap<String,String>();
        hm.put("name", arrayOfString[0].toUpperCase());
        hm.put("type", arrayOfString[1]);
        if (arrayOfString[1].equalsIgnoreCase("string"))
          hm.put("value", "");
        else if (arrayOfString[1].equalsIgnoreCase("int"))
          hm.put("value", "0");
        saasBuffer.add(hm);
      }
     }
    catch (IOException localIOException)
    {
      throw new RuntimeException("[init]缓存域初始化失败!");
    }finally{
    	 try {
			br.close();
			 fr.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }
  }

  public void setHttpBuffer(Buffer paramBuffer)
  {
    httpBuffer = paramBuffer;
  }

  public Buffer getHttpBuffer()
  {
    return httpBuffer;
  }

  public void setBean(Object paramObject)
  {
    vo = paramObject;
  }

  public Object getFormBean()
  {
    return vo;
  }

  public String getClassName()
  {
    return className;
  }

  public void setClassName(String paramString)
  {
    className = paramString;
  }

  public Buffer convert(HttpServletRequest request, Object model, HttpSession session)
  {
    setCommenFields(saasBuffer, httpBuffer);
    setUserSessionFields(session,httpBuffer);
    setString("REALPATH", session.getServletContext().getRealPath(""));
    setString("WEBPATH", request.getHeader("referer"));
    Iterator it = saasBuffer.iterator();
    while (it.hasNext())
    {
      HashMap saBuff = (HashMap)it.next();
      if (saBuff.get("name") != null)
      {
        if (request.getParameter(saBuff.get("name").toString().toLowerCase()) != null)
        {
          addField(saBuff.get("name").toString(), saasBuffer, httpBuffer);
          setString(saBuff.get("name").toString().toUpperCase(), request.getParameter(saBuff.get("name").toString().toLowerCase()).toString());
        }
        Object localObject1;
        try
        {
          Method[] mets = model.getClass().getDeclaredMethods();
          for (int i = 0; i < mets.length; i++)
          {
            if ((!mets[i].getName().startsWith("get")) || (mets[i].getName().equals("getMap")) || (mets[i].getName().equals("getServletWrapper")) || (mets[i].getName().equals("getLog")) || (mets[i].getName().equals("getMultipartRequestHandler")) || (mets[i].getName().equals("getClass")))
              continue;
            String str1 = "";
            if (model.getClass().getDeclaredField(saBuff.get("name").toString().toLowerCase()) != null)
            {
              str1 = model.getClass().getDeclaredField(saBuff.get("name").toString().toLowerCase()).getName();
              Object localObject2 = PropertyUtils.getProperty(model, str1);
              if ((saBuff.get("name").toString().toUpperCase().equalsIgnoreCase(str1.toUpperCase())) && (localObject2 != null))
              {
                addField(saBuff.get("name").toString(), saasBuffer, httpBuffer);
                setString(saBuff.get("name").toString().toUpperCase(), localObject2.toString());
              }
            }
            if ((model.getClass().getDeclaredField(saBuff.get("name").toString().toLowerCase()) == null) || (model.getClass().getDeclaredField(saBuff.get("name").toString().toLowerCase()).getType().getName() != "org.apache.struts.upload.FormFile"))
              break;
            str1 = model.getClass().getDeclaredField(saBuff.get("name").toString().toLowerCase()).getName();
            File file = (File)PropertyUtils.getProperty(model, str1);
            if (file.length() > 0)
            {
              String str2 = comm.GenTradeId();
              String str3 = saveUploadFile(file, request, session, str2);
              String str5 = file.getName();
              try
              {
                log.LOG_INFO("file_name===" + file.getName() + "|===>");
                log.LOG_INFO("filePath===" + str3 + "|===>");
              }
              catch (Exception localException2)
              {
                log.LOG_INFO("FormFormate::::" + localException2.getMessage());
              }
              setString("UPLOADFILEDIR", str3);
              setString("FILE_NAME", str5);
              setString(saBuff.get("name").toString().toUpperCase(), file.toString());
              log.LOG_INFO("FormFile::::" + file.toString());
            }
            else
            {
              setString("UPLOADFILEDIR", "");
              setString(saBuff.get("name").toString().toUpperCase(), file.toString());
            }
            break;
          }
        }
        catch (IllegalAccessException localIllegalAccessException)
        {
          throw new RuntimeException(localIllegalAccessException);
        }
        catch (InvocationTargetException localInvocationTargetException)
        {
          throw new RuntimeException(localInvocationTargetException);
        }
        catch (NoSuchMethodException localNoSuchMethodException)
        {
          throw new RuntimeException(localNoSuchMethodException);
        }
        catch (NoSuchFieldException localNoSuchFieldException)
        {
        }
        catch (Exception localException1)
        {
          localException1.printStackTrace();
        }
      }
    }
    log.LOG_INFO("********本次业务提交初始化域字段列表开始************************");
    list();
    log.LOG_INFO("********本次业务提交初始化域字段列表结束************************");
    return (Buffer)(Buffer)null;
  }

  public void clear()
  {
  }

  public void setString(String paramString1, String paramString2)
  {
    if (httpBuffer.isEmpty())
      throw new RuntimeException(" in Buffer is Empty");
    if (checkContainsKey(paramString1, httpBuffer) == 0)
      addField(paramString1, saasBuffer, httpBuffer);
    Iterator localIterator = httpBuffer.iterator();
    while (localIterator.hasNext())
    {
      HashMap localHashMap = (HashMap)localIterator.next();
      if ((localHashMap.get("name") != null) && (localHashMap.get("name").toString().toUpperCase().equalsIgnoreCase(paramString1.toUpperCase())))
      {
        localHashMap.put("value", paramString2);
        break;
      }
      if (!localIterator.hasNext())
        throw new RuntimeException("[" + paramString1 + "]域字段不存在,[setString]操作失败!");
    }
  }

  public void setInt(String paramString, int paramInt)
  {
    if (httpBuffer.isEmpty())
      throw new RuntimeException("Buffer is Empty");
    if (checkContainsKey(paramString, httpBuffer) == 0)
      addField(paramString, saasBuffer, httpBuffer);
    String str = String.valueOf(paramInt);
    Iterator localIterator = httpBuffer.iterator();
    while (localIterator.hasNext())
    {
      HashMap localHashMap = (HashMap)localIterator.next();
      if ((localHashMap.get("name") != null) && (localHashMap.get("name").toString().toUpperCase().equalsIgnoreCase(paramString.toUpperCase())))
      {
        localHashMap.put("value", str);
        break;
      }
      if (!localIterator.hasNext())
        throw new RuntimeException("[" + paramString + "]域字段不存在,[setInt]赋值操作失败!");
    }
  }

  public String getString(String paramString)
  {
    if (httpBuffer.isEmpty())
      throw new RuntimeException("缓存还没有初始化,[getString]操作失败!");
    String str = "";
    Iterator it = httpBuffer.iterator();
    while (it.hasNext())
    {
      HashMap localHashMap = (HashMap)it.next();
      if ((localHashMap.get("name") != null) && (localHashMap.get("name").toString().toUpperCase().equalsIgnoreCase(paramString.toUpperCase())))
      {
        if (localHashMap.get("type").toString().equalsIgnoreCase("string"))
        {
          if (localHashMap.get("value") == null)
            break;
          if (localHashMap.get("value").equals(""))
          {
            str = "";
            break;
          }
          str = localHashMap.get("value").toString();
          break;
        }
        throw new RuntimeException("类型不匹配,字段[" + paramString + "]不是字符串类型,[getString]操作失败!");
      }
    }
    return convetStrToDb(str);
  }

  public String getStringWeb(String key)
  {
    if (httpBuffer.isEmpty())
      throw new RuntimeException("缓存还没有初始化,[getString]操作失败!");
    String str = "";
    Iterator localIterator = httpBuffer.iterator();
    while (localIterator.hasNext())
    {
      HashMap hm = (HashMap)localIterator.next();
      if ((hm.get("name") != null) && (hm.get("name").toString().toUpperCase().equalsIgnoreCase(key.toUpperCase())))
      {
        if (hm.get("type").toString().trim().equalsIgnoreCase("string"))
        {
          if (hm.get("value") == null)
            break;
          if (hm.get("value").equals(""))
          {
            str = "";
            break;
          }
          str = hm.get("value").toString();
          break;
        }
        throw new RuntimeException("类型不匹配,字段[" + key + "]不是字符串类型,[getString]操作失败!");
      }
      if (!localIterator.hasNext())
        throw new RuntimeException("[" + key + "]域字段不存在,[getString]操作失败!");
    }
    return str;
  }

  public int getInt(String paramString)
  {
    if (httpBuffer.isEmpty())
      throw new RuntimeException("缓存还没有初始化,[getInt]操作失败!");
    String str = "";
    Iterator localIterator = httpBuffer.iterator();
    while (localIterator.hasNext())
    {
      HashMap localHashMap = (HashMap)localIterator.next();
      if ((localHashMap.get("name") != null) && (localHashMap.get("name").toString().toUpperCase().equalsIgnoreCase(paramString.toUpperCase())))
      {
        if (localHashMap.get("type").toString().equalsIgnoreCase("int"))
        {
          if (localHashMap.get("value") == null)
            break;
          if (localHashMap.get("value").equals(""))
          {
            str = "0";
            break;
          }
          str = localHashMap.get("value").toString();
          break;
        }
        throw new RuntimeException("类型不匹配,字段[" + paramString + "]不是字符串类型,[getInt]操作失败!");
      }
      if (!localIterator.hasNext())
        throw new RuntimeException("[" + paramString + "]域字段不存在,[getInt]操作失败!");
    }
    return new Integer(str).intValue();
  }

  public Buffer copyFrom(Buffer paramBuffer)
  {
    return null;
  }

 

  public void addField(String paramString, Buffer backBuff, Buffer paramBuff)
  {
    Iterator localIterator = backBuff.iterator();
    while (localIterator.hasNext())
    {
      HashMap localHashMap = (HashMap)localIterator.next();
      if ((localHashMap.get("name") != null) && (localHashMap.get("name").toString().equalsIgnoreCase(paramString)))
      {
        if (checkContainsKey(localHashMap.get("name").toString(), paramBuff) < 0)
          break;
        paramBuff.add(localHashMap);
        break;
      }
    }
  }

  public void addFieldSting(String paramString1, String paramString2, Buffer paramBuffer)
  {
    Iterator localIterator = paramBuffer.iterator();
    while (localIterator.hasNext())
    {
      HashMap localHashMap1 = (HashMap)localIterator.next();
      if ((localHashMap1.get("name") != null) && (!localHashMap1.get("name").toString().equalsIgnoreCase(paramString1)) && (!localIterator.hasNext()))
      {
        HashMap localHashMap2 = new HashMap();
        localHashMap2.put("name", paramString1.toUpperCase());
        localHashMap2.put("type", paramString2);
        if (paramString2.equalsIgnoreCase("string"))
          localHashMap2.put("value", "");
        else if (paramString2.equalsIgnoreCase("int"))
          localHashMap2.put("value", "0");
        paramBuffer.add(localHashMap2);
      }
    }
  }

  public int checkContainsKey(String paramString, Buffer paramBuffer)
  {
    Iterator localIterator = paramBuffer.iterator();
    while (localIterator.hasNext())
    {
      HashMap localHashMap = (HashMap)localIterator.next();
      if ((localHashMap.get("name") != null) && (localHashMap.get("name").toString().equalsIgnoreCase(paramString)))
        return -1;
    }
    return 0;
  }

  public void list()
  {
    if (httpBuffer.isEmpty())
      throw new RuntimeException("缓存还没有初始化,操作失败!");
    Iterator localIterator = httpBuffer.iterator();
    while (localIterator.hasNext())
    {
      HashMap localHashMap = (HashMap)localIterator.next();
      if (localHashMap.get("name") != null)
        if (localHashMap.get("value") != null)
          log.LOG_INFO(localHashMap.get("name") + ":" + convetStrToDb(localHashMap.get("value").toString()));
        else
          log.LOG_INFO(localHashMap.get("name") + ":" + localHashMap.get("value"));
    }
  }

  public String convetStrToDb(String paramString)
  {
    String str = paramString;
    if ((paramString == null) || (paramString == ""))
      str = "";
    return str;
  }

  public String convetStrToWeb(String paramString)
  {
    String str = "";
    if ((paramString == null) || (paramString == ""))
      str = "";
    else
      try
      {
        str = new String(paramString.getBytes("UTF-8"), "ISO8859_1");
      }
      catch (Exception localException)
      {
        throw new RuntimeException(localException);
      }
    if ((paramString == null) || (paramString == ""))
      str = "";
    return str;
  }

  public void setSessionField(String paramString)
  {
    String str = "SESSION";
    if (paramString == "")
      return;
    if (getString("SESSION_STR") != "")
      str = getString("SESSION_STR") + "," + paramString;
    else
      str = str + "," + paramString;
    setString("SESSION_STR", str);
  }

  public int removeSessionField(String paramString)
  {
    return 0;
  }

  public ArrayList getSessionList()
  {
    ArrayList localArrayList = new ArrayList();
    String str = getString("SESSION_STR");
    String[] arrayOfString = str.split(",");
    for (int i = 0; i < arrayOfString.length; i++)
    {
      if (arrayOfString[i].equalsIgnoreCase("SESSION_STR"))
        continue;
      HashMap localHashMap = new HashMap();
      localHashMap.put("name", arrayOfString[i]);
      localArrayList.add(localHashMap);
    }
    return localArrayList;
  }

  public String getSessionField(String paramString)
  {
    String str1 = "";
    String str2 = getString("SESSION_STR");
    if (str2.indexOf(paramString) > 0)
      str1 = paramString;
    return str1;
  }

  public void setCommenFields(Buffer backBuff, Buffer paramBuff)
  {
    addField("SUCCEED_FWD", backBuff, paramBuff);
    addField("ERROR_FWD", backBuff, paramBuff);
    addField("SESSION_STR", backBuff, paramBuff);
    addField("RESULT_CODE", backBuff, paramBuff);
    addField("RESULT_INFO", backBuff, paramBuff);
    addField("OUT_QUERY", backBuff, paramBuff);
    addField("OUT_BUFFER", backBuff, paramBuff);
    addField("SESSION", backBuff, paramBuff);
    addField("REALPATH", backBuff, paramBuff);
  }
  
  public void setUserSessionFields(HttpSession session,Buffer httpBuffer)
  {
	  if ((session != null) && (session.getAttribute("OLUSER") != null))
      {
		UserCore uc = (UserCore)session.getAttribute("OLUSER");
        addField("SESSION_USER_ID", saasBuffer, httpBuffer);
        setString("SESSION_USER_ID", uc.getUserId());
        
        addField("SESSION_CUST_TYPE", saasBuffer, httpBuffer);
        setString("SESSION_CUST_TYPE", uc.getCustType());
        
        addField("SESSION_CUST_NAME", saasBuffer, httpBuffer);
        setString("SESSION_CUST_NAME", uc.getCustName());
        
        addField("SESSION_CUST_ID", saasBuffer, httpBuffer);
        setString("SESSION_CUST_ID", uc.getCustId());
        
        addField("SESSION_USER_NAME", saasBuffer, httpBuffer);
        setString("SESSION_USER_NAME", uc.getUserName());
        
        addField("SESSION_USER_TYPE", saasBuffer, httpBuffer);
        setString("SESSION_USER_TYPE", uc.getUserType());
        
        addField("SESSION_CONTACT_NAME", saasBuffer, httpBuffer);
        setString("SESSION_CONTACT_NAME", uc.getContactName());
        
        addField("SESSION_ROLE_CODE", saasBuffer, httpBuffer);
        setString("SESSION_ROLE_CODE", uc.getRoleAuthId());
      }
  }

  public String saveUploadFile(File file, HttpServletRequest request, HttpSession paramHttpSession, String paramString)
  {
    String str2 = file.getName();
    str2 = str2.substring(str2.length() - 4);
    String str6 = "";
    ParamInfo localParamInfo = new ParamInfo();
    try
    {
      str6 = localParamInfo.getParameter("yinroot_path");
    }
    catch (SaasApplicationException localSaasApplicationException)
    {
      localSaasApplicationException.printStackTrace();
    }
    String str7 = String.valueOf(paramHttpSession.getAttribute("SESSION_CUST_ID"));
    String str8 = "";
    if (request.getParameter("department") != null)
      str8 = request.getParameter("department");
    String str9 = str6 + "/upload/" + str7 + "/" + paramString + str2;
    String str10 = "/upload/" + str7 + "/" + paramString + str2;
    if ((str8 != null) && (!"".equals(str8)))
    {
      str9 = str6 + "/upload/department/" + request.getParameter("department_id") + "/" + paramString + str2;
      str10 = "/upload/department/" + request.getParameter("department_id") + "/" + paramString + str2;
    }
    try
    {
      File localFile = new File(str6 + "/upload/" + str7);
      if ((str8 != null) && (!"".equals(str8)))
        localFile = new File(str6 + "/upload/department/" + request.getParameter("department_id"));
      if (!localFile.exists())
        try
        {
          localFile.mkdirs();
        }
        catch (Exception localException)
        {
          log.LOG_INFO("创建文件夹失败！");
        }

      InputStream localInputStream = new FileInputStream(file);;
      FileOutputStream localFileOutputStream = new FileOutputStream(str9);
      int i = 0;
      byte[] arrayOfByte = new byte[8192];
      while ((i = localInputStream.read(arrayOfByte, 0, 8192)) != -1)
        localFileOutputStream.write(arrayOfByte, 0, i);
      localFileOutputStream.close();
      localInputStream.close();
    }
    catch (IOException localIOException)
    {
      throw new RuntimeException(localIOException);
    }
    return str10;
  }

  public ArrayList buffersToBuffer(Buffers paramBuffers)
  {
    Buffer localBuffer = new Buffer();
    Iterator localIterator = httpBuffer.iterator();
    while (localIterator.hasNext())
    {
      HashMap localHashMap1 = (HashMap)localIterator.next();
      if (localHashMap1.get("name") != null)
      {
        HashMap localHashMap2 = new HashMap();
        localHashMap2.put(localHashMap1.get("name").toString(), localHashMap1.get("value"));
        localBuffer.add(localHashMap2);
      }
    }
    return localBuffer;
  }

  public ArrayList BuffersToArrayList(Buffers paramBuffers)
  {
    Buffer localBuffer = new Buffer();
    Iterator localIterator = httpBuffer.iterator();
    while (localIterator.hasNext())
    {
      HashMap localHashMap1 = (HashMap)localIterator.next();
      if (localHashMap1.get("name") != null)
      {
        HashMap localHashMap2 = new HashMap();
        localHashMap2.put("type", localHashMap1.get("type").toString());
        localHashMap2.put("name", localHashMap1.get("name").toString());
        localHashMap2.put("value", localHashMap1.get("value"));
        localBuffer.add(localHashMap2);
      }
    }
    return localBuffer;
  }

  public boolean isFieldExist(String paramString)
  {
    return getString(paramString) != null;
  }

}

